<template>
  <view class="container">
    <uni-forms
      ref="formRef"
      label-position="top"
      :model="formData"
      :rules="rules"
      label-width="100vw"
    >
      <template v-for="item in formOption">
        <slot
          :name="`before${item.prop}`"
          :formData="formData"
          :option="item"
        ></slot>
        <slot :name="item.prop" :formData="formData" :option="item">
          <uni-forms-item
            :key="item.prop"
            :label="item.label"
            :required="item.required"
            :rules="
              item.required
                ? [
                    {
                      required: true,
                      errorMessage: '字段为必填项',
                    },
                  ]
                : []
            "
            :name="item.prop"
          >
            <uni-easyinput
              :style="{
                border: 'none',
              }"
              v-if="item.type == 'input'"
              @change="changeInput(item, $event)"
              type="text"
              v-model="formData[item.prop]"
            />
            <uni-data-select
              style="border: none"
              v-else-if="item.type == 'select'"
              v-model="formData[item.prop]"
              :localdata="item.optionItems"
              @change="change(item.prop, $event)"
            ></uni-data-select>
            <view v-else-if="item.type == 'userselect'">
              <UserSelect
                :userList="formData.jobPersonnel"
                @change="userChange"
              ></UserSelect>
              <uni-table ref="table" border stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th width="50" align="center">姓名</uni-th>
                  <!-- <uni-th width="100" align="center">证书编号</uni-th> -->
                  <uni-th width="80" align="center">人员类型</uni-th>
                  <uni-th width="50" align="center">操作</uni-th>
                </uni-tr>
                <uni-tr
                  v-for="(item, index) in formData.jobPersonnel"
                  :key="index"
                >
                  <uni-td>{{ item.nickName || item.name }}</uni-td>
                  <!-- <uni-td>
                    {{ item.zsh || "无" }}
                  </uni-td> -->
                  <uni-td>
                    {{ item.type == "in" ? "内部人员" : "外部人员" }}
                  </uni-td>
                  <uni-td>
                    <text
                      style="color: red"
                      @click="delZyry(index, item)"
                      size="mini"
                      >删除</text
                    >
                  </uni-td>
                </uni-tr>
              </uni-table>
            </view>
            <xtyh
              v-else-if="item.type == 'xtyh'"
              :names="formData[item.prop]"
              @change="onUserChange(item.prop, $event)"
              :limit="1"
            ></xtyh>

            <uni-data-select
              v-else-if="item.type == 'zyry'"
              :localdata="selectZyry"
              v-model="formData[item.prop]"
              @change="changeZyry(item, $event)"
            ></uni-data-select>

            <rudon-multiSelector
              v-else-if="item.type == 'zllx'"
              welcome="请选择"
              :is_using_slot="false"
              :is_using_icon="true"
              :localdata="jobTypeList"
              v-model="formData[item.prop]"
            ></rudon-multiSelector>
            <uni-datetime-picker
              v-else-if="
                [
                  'datetime',
                  'date',
                  'datetimerange',
                  'daterange',
                  'time',
                ].includes(item.type)
              "
              :type="item.type"
              v-model="formData[item.prop]"
              @change="change(item.prop, $event, item.type)"
              :hide-second="true"
            />
            <uni-data-checkbox
              v-else-if="item.type == 'radio' || item.type == 'checkbox'"
              v-model="formData[item.prop]"
              :localdata="item.optionItems"
              :multiple="item.type == 'checkbox'"
              @change="change(item.prop, $event)"
            ></uni-data-checkbox>
          </uni-forms-item>
        </slot>
      </template>
    </uni-forms>
    <button type="primary" @click="submitForm">提 交</button>
  </view>
</template>

<script setup>
import { onMounted, ref, defineProps, defineEmits, watch } from "vue";
import { formatDate } from "@/utils/index.js";
import UserSelect from "./selectUser.vue";
import xtyh from "@/components/user-select.vue";
import { getData } from "@/api/autha";
const emits = defineEmits(["onChange", "onSubmit"]);
const props = defineProps({
  rules: {
    type: Object,
    default: () => ({}),
  },
  formOption: {
    type: Array,
    default: () => [],
  },
  jobType: [String, Number],
});

const submitForm = async () => {
  const res = await getFormData();
  if (res) {
    emits("onSubmit", { ...keepData.value, ...formData.value });
  } else {
    return false;
  }
};
const formData = ref({
  declareType: "",
});
const keepData = ref({
  jobPersonnel: [],
});
function setFormData(data = {}) {
  keepData.value = JSON.parse(JSON.stringify(data));
  formData.value = { ...data };
}

const formRef = ref();
async function getFormData() {
  try {
    const res = await formRef.value.validate();
    return res;
  } catch (e) {
    return false;
  }
}
const userChange = (e) => {
  formData.value.jobPersonnel = formData.value.jobPersonnel || [];
  formData.value.jobPersonnel = [...formData.value.jobPersonnel, ...e.list];
  if (e.removeIds && e.removeIds.length) {
    for (let i = 0; i < e.removeIds.length; i++) {
      let findIndex = formData.value.jobPersonnel.findIndex(item => item.id === e.removeIds[i])
      if(findIndex !== -1) {
        formData.value.jobPersonnel.splice(findIndex, 1)
      }
    }
  }
  e.done();
};
const onUserChange = (key, e) => {
  if (e.list.length > 0) {
    formData.value[key + "Id"] = e.ids;
    formData.value[key] = e.names;
    e.done(formData.value[key + "Name"]);
  } else {
    e.done("");
  }
};
const jobTypeList = ref([]);
getData("sys_zygl_zylx").then((res) => {
  jobTypeList.value = res.data.map((ele) => ({
    text: ele.dictLabel,
    value: ele.dictLabel,
  }));
});
const change = (key, value) => {
  emits("onChange", {
    key,
    value,
  });
};

defineExpose({
  setFormData,
  getFormData,
});
const selectZyry = ref([]);
watch(
  () => formData.value.jobPersonnel,
  () => {
    selectZyry.value = formData.value.jobPersonnel.map((item) => ({
      value: item.name,
      text: item.name,
      id: item.id,
    }));
  }
);

// 选择作业人员 自动匹配id
const changeZyry = (option, val) => {
  const ry = selectZyry.value.find((item) => val == item.value);
  if (ry) {
    formData.value[option.prop + "Id"] = ry.id;
  }
};

// 删除作业人员
const delZyry = (index) => {
  formData.value.jobPersonnel.splice(index, 1);
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #fff !important;
}
.is-input-border {
  border: none !important;
}
.container {
  padding: 16px;
  background-color: #fff !important;
}
.checklist-group {
  padding: 10px;
}
</style>
